package com.ssmeasy.jdgl.intercepter;

import com.ssmeasy.jdgl.pojo.User;
import com.ssmeasy.jdgl.service.UserService;
import com.ssmeasy.jdgl.utils.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LoginInterceptor implements HandlerInterceptor {

	@Autowired
	private UserService userService;

	/**
	 * 前置拦截 验证登陆
	 * 成功进入控制层
	 * 失败返回401
	 *
	 * @param request
	 * @param response
	 * @param o
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
	   //获取cookie中username对应的对象
		User user = userService.getByUsername(CookieUtils.getCookie(request,"username"));
	    if(user!= null)
	        return true;

	    //验证失败返回401错误（未授权）
	    response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"未登录");
	    return false;
	}

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
